const userInput = document.getElementById('userInput');
const chatHistory = document.getElementById('chatHistory');
const loading = document.getElementById('loading');
let currentImageUrl = null;

// 按Enter发送消息
userInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        sendMessage();
    }
});

async function handleImageUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('image', file);

    try {
        loading.style.display = 'block';
        const response = await fetch('/api/upload', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();
        if (data.success) {
            currentImageUrl = data.data.url;
            showImagePreview(file);
        } else {
            alert('图片上传失败：' + data.message);
        }
    } catch (error) {
        alert('图片上传失败，请重试');
    } finally {
        loading.style.display = 'none';
    }
}

function showImagePreview(file) {
    const preview = document.getElementById('imagePreview');
    const previewImage = document.getElementById('previewImage');
    
    const reader = new FileReader();
    reader.onload = function(e) {
        previewImage.src = e.target.result;
        preview.classList.remove('hidden');
    }
    reader.readAsDataURL(file);
}

function removeImage() {
    currentImageUrl = null;
    document.getElementById('imagePreview').classList.add('hidden');
    document.getElementById('imageInput').value = '';
}

async function sendMessage() {
    const query = userInput.value.trim();
    if (!query) return;

    appendMessage('user', query);
    if (currentImageUrl) {
        appendMessage('user', `<img src="${currentImageUrl}" class="max-h-48 rounded-lg">`);
    }
    userInput.value = '';

    loading.style.display = 'block';

    try {
        const response = await fetch('/api/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                query: query,
                image_url: currentImageUrl
            })
        });

        const data = await response.json();
        
        if (data.success) {
            appendMessage('assistant', data.data.response);
        } else {
            appendMessage('assistant', '抱歉，发生了一些错误：' + data.message);
        }
    } catch (error) {
        appendMessage('assistant', '抱歉，服务器出现问题，请稍后再试。');
    }

    loading.style.display = 'none';
    removeImage();
}

function appendMessage(role, content) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'flex items-start space-x-4 fade-in';
    
    const avatar = role === 'user' ? '游客' : 'AI';
    const bgColor = role === 'user' ? 'bg-green-50' : 'bg-blue-50';

    messageDiv.innerHTML = `
        <div class="flex-shrink-0">
            <div class="w-10 h-10 rounded-full gradient-bg flex items-center justify-center">
                <span class="text-white font-bold">${avatar}</span>
            </div>
        </div>
        <div class="flex-1 ${bgColor} rounded-lg p-4">
            <div class="text-gray-800">${content}</div>
        </div>
    `;

    chatHistory.appendChild(messageDiv);
    chatHistory.scrollTop = chatHistory.scrollHeight;
}